// 对象转化成url
let urlEncode = function(param, key, encode) {
  if (param == null) return "";
  var paramStr = "";
  var t = typeof param;
  if (t == "string" || t == "number" || t == "boolean") {
    paramStr +=
      "&" +
      key +
      "=" +
      (encode == null || encode ? encodeURIComponent(param) : param);
  } else {
    for (var i in param) {
      var k =
        key == null
          ? i
          : key + (param instanceof Array ? "[" + i + "]" : "." + i);
      paramStr += urlEncode(param[i], k, encode);
    }
  }
  return paramStr;
};
// 将表单数据添加defaultValue
let addInitialValue = function(formList, value) {
  formList.formList.forEach(item => {
    item.initialValue = value[item.name];
  });
  return formList;
};
let toMoney = function(num) {
  if (num || num === 0) {
    if (isNaN(num)) {
      alert("金额中含有不能识别的字符");
      return;
    }
    num = typeof num == "string" ? parseFloat(num) : num; //判断是否是字符串如果是字符串转成数字
    num = num.toFixed(2); //保留两位
    num = parseFloat(num); //转成数字
    num = num.toLocaleString(); //转成金额显示模式
    //判断是否有小数
    if (num.indexOf(".") === -1) {
      num = "￥" + num + ".00";
    } else {
      num = num.split(".")[1].length < 2 ? "￥" + num + "0" : "￥" + num;
    }
    return num; //返回的是字符串23,245.12保留2位小数
  } else {
    return "￥0.00";
  }
};
// 计算字符串的长度
let strlen = function(str) {
  var len = 0;
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    //单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      len++;
    } else {
      len += 2;
    }
  }
  return len;
};
// 截取长度为多少的字符串
let str = function(str, length) {
  var len = 0;
  let newStr = "";
  for (var i = 0; i < str.length; i++) {
    var c = str.charCodeAt(i);
    //单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      len++;
    } else {
      len += 2;
    }
    if (len < length) {
      newStr = newStr + str[i];
    } else {
      return newStr + "...";
    }
  }
  if (len < length) {
    return newStr;
  }
};
export { urlEncode, addInitialValue, toMoney, strlen, str };
